<template>
	<div class="system-role-container layout-padding">
		<div class="system-role-padding layout-padding-auto layout-padding-view">
			<TableSearch :search="state.tableData.search" @search="onSearch" />

			<Table ref="tableRef" v-bind="state.tableData" class="table-demo" @selectionTable="handleSelectionTable"
				@pageChange="onTablePageChange" @sortHeader="onSortHeader">
				<template #header>
					<el-button type="primary" @click="onOpenAddRole('add')">新增</el-button>
					<el-button type="danger" @click="batchDelete">批量删除</el-button>
				</template>

				<template #actionCol="{ row }">
					<el-button text size="small" type="primary" @click="onOpenEditRole('edit',row)">编辑</el-button>
					<el-button text size="small" type="primary" @click="onOpenAssign(row)">分配菜单</el-button>
					<el-popconfirm title="确定删除吗？" @confirm="onTableDelRow(row)">
						<template #reference>
							<el-button text size="small" type="primary">删除</el-button>
						</template>
					</el-popconfirm>
				</template>
			</Table>
		</div>
		<RoleDialog ref="roleDialogRef" @refresh="getTableData()" />
		<SelectMenu ref="selectMenuRef" @handleSubmit="submit" />
	</div>
</template>

<script setup name="systemRole">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { Role, Menu } from '/@/api'

// 引入组件
const RoleDialog = defineAsyncComponent(() => import('/@/views/system/role/dialog.vue'));
const SelectMenu = defineAsyncComponent(() => import('/@/views/system/menu/selectMenu.vue'));


// 引入组件
const Table = defineAsyncComponent(() => import('/@/components/table/index.vue'));
const TableSearch = defineAsyncComponent(() => import('/@/components/table/search.vue'));

// 定义变量内容
const tableRef = ref();
const state = reactive({
	tableData: {
		// 列表数据（必传）
		data: [],
		// 表头内容（必传，注意格式）
		header: [
			{ key: 'name', colWidth: '', title: '角色名称', type: 'text', isCheck: true },
			{ key: 'roleSign', colWidth: '', title: '角色标识', type: 'text', isCheck: true },
			{ key: 'isValid', colWidth: '', title: '角色状态', type: 'text', isCheck: true },
			{ key: 'isAdmin', colWidth: '', title: '是否管理员', type: 'text', isCheck: true },
			{ key: 'note', colWidth: '', title: '备注', type: 'text', isCheck: true },
			{ key: 'createTime', colWidth: '', width: '70', height: '40', title: '创建时间', type: 'text', isCheck: true },
			{ key: 'createBy', colWidth: '', width: '70', height: '40', title: '创建人', type: 'text', isCheck: true },

		],
		// 配置项（必传）
		config: {
			total: 0, // 列表总数
			loading: true, // loading 加载
			isBorder: true, // 是否显示表格边框
			isSerialNo: true, // 是否显示表格序号
			isSelection: true, // 是否显示表格多选
			isOperate: true, // 是否显示表格操作栏
			isShowTool: true,//是否显示表头工具栏
		},
		// 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
		search: [
			{ label: '角色名称', prop: 'name', placeholder: '请输入角色名称', required: false, type: 'input' },
			{
				label: '是否有效',
				prop: 'isValid',
				placeholder: '请选择',
				required: false,
				type: 'select',
				options: [
					{ label: '有效', value: 1 },
					{ label: '无效', value: 0 },
				],
			},
		],
		// 搜索参数（不用传，用于分页、搜索时传给后台的值，`getTableData` 中使用）
		param: {
			pageNum: 1,
			pageSize: 10,
			conditions: []

		},
		//设置页面进入初始化一直使用的参数条件
		initConditions: [],

		// 打印标题
		printName: 'vueNextAdmin 表格打印演示',
	},
});

// 初始化列表数据
const getTableData = async () => {
	state.tableData.config.loading = true;
	await Role.postRoleList(state.tableData.param).then(res => {
		if (res.data) {
			state.tableData.data = res.data.list
			state.tableData.config.total = res.data.total
		}
	})
	// 数据总数（模拟，真实从接口取）
	setTimeout(() => {
		state.tableData.config.loading = false;
	}, 500);
};
// 搜索点击时表单回调
const onSearch = (condit) => {
	state.tableData.param.conditions = [];
	state.tableData.param.conditions = [...state.tableData.initConditions, ...condit]
	getTableData()
};

const checkList = ref([]);
const handleSelectionTable = (selectlist) => {
	checkList.value = selectlist
}

const batchDelete = () => {
	if (checkList.value.length == 0) {
		ElMessage.error("至少选中一条数据")
	} else {
		ElMessageBox.confirm(
			'是否确认要删除数据?',
			'Warning',
			{
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				let idArr = []
				checkList.value.forEach(e => {
					idArr.push(e.id)
				});
				let ids = idArr.join(',')
				console.log(ids);
				//删除接口
				ElMessage({
					type: 'success',
					message: ids,
				})
			})


	}
}

// 删除当前项回调
const onTableDelRow = async (row) => {
	await Role.delRole(row.id).then(res=>	ElMessage.success(`删除${row.name}成功！`));
	getTableData();
};
// 分页改变时回调
const onTablePageChange = (page) => {

	state.tableData.param.pageNum = page.pageNum;
	state.tableData.param.pageSize = page.pageSize;
	getTableData();
};
// 拖动显示列排序回调
const onSortHeader = (data) => {
	state.tableData.header = data;
};
// 页面加载时
onMounted(() => {
	getTableData();
});

const selectMenuRef = ref()
const onOpenAssign = async (row) => {
	let roleId = row.id
	//打开分配菜单弹出框
	console.log(selectMenuRef.value);
	let assignId = roleId
	let initSaveMenuIdsArr = await initRoleMenuLkList(roleId)
	selectMenuRef.value.openAssignDialog(assignId, initSaveMenuIdsArr);
}

const initRoleMenuLkList = (roleId) => {
	let menuId = Menu.getMenuListByRoleId(roleId).then(res =>res.data)
	return menuId//['8', '9', '3221e5faf42d4e4ea7e1e000ea52f6a9', '10', '02d86c929da04de4bb01c3f4615312a0', '11']
}
const submit=async (menuIds,roleId)=>{
	
	///role/assignMenu
	let data = {roleId:roleId,menuIds:menuIds}
	console.log(data)
	await Role.addAssignMenuIds(data).then(res=>ElMessage.success(res.data))
}

// 定义变量内容
const roleDialogRef = ref();

// 打开新增角色弹窗
const onOpenAddRole = (type) => {
	roleDialogRef.value.openDialog(type);
};
// 打开修改角色弹窗
const onOpenEditRole = (type, row) => {
	roleDialogRef.value.openDialog(type, row);
};

</script>

<style scoped lang="scss">
.system-role-container {
	.system-role-padding {
		padding: 15px;

		.el-table {
			flex: 1;
		}
	}
}
</style>
